#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "qcustomplot.h"

#include "QPushButton"
#include "QVBoxLayout"

#include "QsqlDatabase.h"

#include<QHBoxLayout>
#include<QLabel>
#include"QNavWidget.h"
#include<QStackedWidget>

#include<QTextStream>
#include<QMouseEvent>
#include<QToolBar>
#include<QLabel>

#include <QDateTime>
#include<QTime>

//#include "MyThread.h"

#include<string>
#include<QByteArray>

#include <QJsonObject>
#include <QJsonDocument>
#include <QJsonArray>

 QString last_update;

 QString country;     // 国家代码
 QString id;          // 位置ID
 QString name;        // 地名
 QString path;        // 完整路径
 QString timezones;    // 时区名称
 QString timezone_offset; // 时区偏移

 QString clouds;          // 云量
 QString code;            // 天气代码
 QString dew_point;       // 露点温度
 QString feels_like;      // 体感温度
 QString humidity;        // 湿度
 QString pressure;        // 气压
 QString temperature;    // 实际温度
 QString text;            // 天气描述
 QString visibility;      // 能见度
 QString wind_direction;  // 风向
 QString wind_direction_degree;     // 风向角度
 QString wind_scale;      // 风级
 QString wind_speed;      // 风速




MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{

       ui->setupUi(this);  // 先初始化UI

/////////////////////set nav///////////////////
       resize(980, 780);

       QWidget *mainWidget = new QWidget;
       QWidget *rightWidget = new QWidget;

      // QWidget *container = new QWidget;
       QToolBar *toolbar = new QToolBar;
       this->addToolBar(toolbar);

       toolbar->setIconSize(QSize(24, 24));  // 设置图标尺寸为 24x24

       QVBoxLayout *rightLayout = new QVBoxLayout(rightWidget);
       QHBoxLayout *mainLayout = new QHBoxLayout(mainWidget);
    //   QHBoxLayout *timeLayout = new QHBoxLayout(mainWidget);

      // QHBoxLayout *toolbarLayout = new QHBoxLayout(container);


      // toolbar->addWidget(container);


/////////////////////set nav-time///////////////////
       timeLabel = new QLabel(this);
       timeLabel->setAlignment(Qt::AlignVCenter);

       setCentralWidget(timeLabel);

       timer = new QTimer(this);
       connect(timer, &QTimer::timeout, this, &MainWindow::updateTimeDisplay);
       timer->start(1000); // 每秒更新一次
       // 左侧伸展控件
       QWidget *leftSpacer = new QWidget;
       leftSpacer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
       toolbar->addWidget(leftSpacer);

       toolbar->addWidget(timeLabel);
       // 右侧伸展控件
       QWidget *rightSpacer = new QWidget;
       rightSpacer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
       toolbar->addWidget(rightSpacer);
      // timeLayout->addWidget(toolbar);

       QNavigationWidget *navigationWidget = new QNavigationWidget;

       //mainWidget->setFixedWidth(980,780);
       //QLabel *tipsLabel = new QLabel("Item: 0");
       navigationWidget->setRowHeight(60);
       navigationWidget->addItem(":/pic/pic/date.png","Date");
       navigationWidget->addItem(":/pic/pic/Medications","History");
       navigationWidget->addItem(":/pic/pic/pulse.png","Allergies");
       navigationWidget->addItem(":/pic/pic/contacts.png","Medications");
       navigationWidget->addItem(":/pic/fileopen.png","Diet");
       navigationWidget->addItem(":/pic/filesave.png","Contacts");

       //qDebug() << QFile(":/pic/date.png").exists(); // 输出 true 表示路径有效



       /////////////////////set stackPage///////////////////
       QStackedWidget *stack = new QStackedWidget(this);
       // 创建三个示例页面
       QWidget *pageHome = new QWidget();
       pageHome->setStyleSheet("background: #FFE4B5;"); // 橙色背景
       QWidget *pageSettings = new QWidget();
       pageSettings->setStyleSheet("background: #B0E0E6;"); // 蓝色背景
       QWidget *pageHelp = new QWidget();
       pageHelp->setStyleSheet("background: #98FB98;"); // 绿色背景
       QWidget *chartpage = new QWidget();
       pageHelp->setStyleSheet("background: #c17778;"); // 绿色背景
       // 将页面添加到堆叠窗口
       stack->addWidget(pageHome);
       stack->addWidget(pageSettings);
       stack->addWidget(pageHelp);
       stack->addWidget(chartpage);//page

       mainLayout->addWidget(navigationWidget,0);
       mainLayout->addWidget(stack,1);

       // 绑定导航点击信号到堆叠窗口切换
       connect(navigationWidget, &QNavigationWidget::currentItemChanged,
              stack, &QStackedWidget::setCurrentIndex);

       /**
       connect(navigationWidget, &QNavigationWidget::currentItemChanged, this, [=](const int &current){
           QTipLabel->setText("Item: " + QString::number(current));
       });
**/


 ///////////////////////////set graph///////////////////
    // 创建QCustomPlot并直接挂载到MainWindow的centralWidget

    QCustomPlot *myPlot = new QCustomPlot(chartpage);

    // 设置图表尺寸和布局
    myPlot->setFixedSize(680, 480);
    myPlot->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);

    // 添加图表样式
    myPlot->addGraph();
    myPlot->graph(0)->setPen(QPen(Qt::blue));

    // 设置坐标轴范围和标签
    myPlot->axisRect()->setupFullAxesBox();
    myPlot->xAxis->setRange(0, 10);      // 扩大x轴范围
    myPlot->yAxis->setRange(0, 100);     // 扩大y轴范围
    myPlot->xAxis->setLabel("I(A)");
    myPlot->yAxis->setLabel("U(V)");



    // 将图表添加到布局（可选，若centralWidget已有布局）
    if (!ui->centralwidget->layout()) {
        stack->addWidget(chartpage);

    } else {
        ui->centralwidget->layout()->addWidget(myPlot);

    }


    //set graph value
    QVector<double> x,y;   //创建QVector，用来保存x轴和y轴的值
       //设置保存x轴和y轴的值
       for(double xi=-2*M_PI;xi<2*M_PI;xi+=0.1)
       {
           x.push_back(xi);
           y.push_back(sin(xi));
       }
       myPlot->addGraph(0);  //新增一个曲线
       myPlot->graph(0)->setData(x,y);//设置曲线的值，绘制曲线
       myPlot->graph(0)->setName("y=sin(x)");//设置曲线名称
       myPlot->rescaleAxes(true);  //根据当前数据自动设置轴的范围
       myPlot->xAxis->setLabel("X下");  //设置轴的名称
       myPlot->yAxis->setLabel("Y左");  //设置轴的名称
       myPlot->xAxis2->setLabel("X上");  //设置轴的名称，默认不显示
       myPlot->yAxis2->setLabel("Y右");  //设置轴的名称，默认不显示
       myPlot->legend->setVisible(true);

       //增加部分
       QPen pen;
       pen.setColor(Qt::red);  //设置曲线颜色为红色
       pen.setStyle(Qt::DotLine);//设置曲线为虚线
       pen.setWidth(3);//设置线宽
       myPlot->graph(0)->setPen(pen);  //设置曲线使用QPen绘制
       myPlot->graph(0)->setBrush(QBrush(QColor(255,50,30,20)));//使用QBrush给曲线之间填充颜色

  /**
  //button
       // 创建一个按钮
       QPushButton *button = new QPushButton("Click Me", pageHome);
       // 设置按钮的位置和大小（可选）
       button->setGeometry(100, 200, 100, 30);


        extern  QString country;
       const char* fromQstr = country.toUtf8().constData();
       std::cout<<"fromQstr: "<<fromQstr;

       button->setText(fromQstr); // 设置按钮上的文本

       button->setToolTip("This is a INSERT");
       connect(button, &QPushButton::clicked, this, &MainWindow::onButtonClicked);

       QLabel *label = new QLabel(pageHome);
       label->setText(fromQstr);
       label->show();
**/
       QNetworkAccessManager *manager = new QNetworkAccessManager(this);
       QNetworkRequest request(QUrl("https://api.seniverse.com/v3/weather/now.json?key=SozYmp2ySytux_l4Y&location=beijing&language=zh-Hans&unit=c"));
       QNetworkReply *reply = manager->get(request);
        connect(reply, &QNetworkReply::finished, this, &MainWindow::loadJsonData);
       /////////////////////set jsonWidget///////////////////




       /////////////////////set pageMain///////////////////


       setCentralWidget(mainWidget);
       /////////////////////set style//////////////////////

       QFile qss_file(":/cssstyle/CSS/csstyle.qss");
       if (qss_file.open(QFile::ReadOnly)) {
           QTextStream filetext(&qss_file);
           QString stylesheet = filetext.readAll();
           this->setStyleSheet(stylesheet);
           qDebug() << QFile(":/cssstyle/CSS/csstyle.qss").exists();
           qss_file.close();
       }
   /**
       // 服务端启动
       Server server;
       server.startServer();

       // 客户端使用
       //Client client;
       //client.connectToServer("https://api.seniverse.com/v3/weather/now.json?key=SozYmp2ySytux_l4Y&location=beijing&language=zh-Hans&unit=c", 443);
      // client.onReadyRead();

     //  client.sendMessage("Hello Server!");

       ApiClient api;
       api.fetchData();
       api.onReplyFinished();
 **/
       /////////////////////set network//////////////////////
/**
        QNetworkAccessManager *manager = new QNetworkAccessManager(this);
        connect(manager, &QNetworkAccessManager::finished,
                this, &MyClass::replyFinished);

        manager->get(QNetworkRequest(QUrl("http://qt-project.org")));
        QNetworkRequest request;
        request.setUrl(QUrl("http://qt-project.org"));
         // request.setRawHeader("User-Agent", "MyOwnBrowser 1.0");

        QNetworkReply *reply = manager->get(request);
        connect(reply, &QIODevice::readyRead, this, &MyClass::slotReadyRead);
        connect(reply, QOverload<QNetworkReply::NetworkError>::of(&QNetworkReply::error),
                  this, &MyClass::slotError);
        connect(reply, &QNetworkReply::sslErrors,
                  this, &MyClass::slotSslErrors);
**/
      // myThread t;
       //t.start();
}

void MainWindow::loadJsonData() {
    QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender());
    if (reply->error() == QNetworkReply::NoError) {

        QByteArray responseDate = reply->readAll();

        qDebug() << "1 replay = "<<responseDate;

        QString responseString = QString::fromUtf8(responseDate);
        QJsonDocument doc = QJsonDocument::fromJson(responseDate);
        if (!doc.isNull() && doc.isObject()) {

             QJsonObject roots = doc.object();
             QJsonArray resultsArr = roots["results"].toArray();

             qDebug() << "2 resultArr = "<<resultsArr;
                for(const QJsonValue &value:resultsArr)
                {
                    if(value.isObject()){
                        QJsonObject obj = value.toObject();
                         last_update = obj["last_update"].toString();

                        QJsonObject location = value["location"].toObject();
                     //   if(location.contains("country") && location.contains("id") && location.contains("name") && location.contains("timezones") && location.contains("timezone_offset") ){

                            country = location["country"].toString();
                            id = location["id"].toString();
                            name = location["name"].toString();
                            timezones = location["timezones"].toString();
                            timezone_offset = location["timezone_offset"].toString();



                        QJsonObject now = value["now"].toObject();
                          clouds = now["clouds"].toString();
                          code = now["code"].toString();
                          dew_point = now["dew_point"].toString();
                          feels_like = now["feels_like"].toString();
                          humidity = now["humidity"].toString();
                          pressure = now["pressure"].toString();
                          temperature = now["temperature"].toString();
                          text = now["text"].toString();
                          visibility = now["visibility"].toString();
                          wind_direction = now["wind_direction"].toString();
                          wind_direction_degree = now["wind_direction_degree"].toString();
                          wind_scale = now["wind_scale"].toString();
                          wind_speed = now["wind_speed"].toString();

                          jsonWidget = new QWidget();

                          countryLabel = new QLabel(this);
                          idLabel = new QLabel(this);
                          nameLabel = new QLabel(this);
                          timezoneLabel = new QLabel(this);
                          timezone_offsetLabel = new QLabel(this);


                          QVBoxLayout *jsonLayout = new QVBoxLayout();

                          jsonLayout->addWidget(jsonWidget);
                          jsonLayout->addWidget(countryLabel);
                          jsonLayout->addWidget(idLabel);
                          jsonLayout->addWidget(nameLabel);
                          jsonLayout->addWidget(timezoneLabel);
                          jsonLayout->addWidget(timezone_offsetLabel);

                          countryLabel->setText(country);
                          countryLabel->show();
                          countryLabel->setStyleSheet("QLabel {color : red}");
                          idLabel->setText(id);
                          idLabel->show();
                          nameLabel->setText(name);
                          nameLabel->show();
                          timezoneLabel->setText(timezones);
                          timezoneLabel->show();
                          timezone_offsetLabel->setText(timezone_offset);
                          timezone_offsetLabel->show();


                          jsonWidget->setGeometry(200,400,300,200);
                            countryLabel->setGeometry(200,100,100,50);
                            idLabel->setGeometry(200,100,100,100);
                            nameLabel->setGeometry(200,100,100,150);
                            timezoneLabel->setGeometry(200,100,100,200);
                            timezone_offsetLabel->setGeometry(200,100,100,250);


                         // connect(connectl, &QPushButton::clicked, this, &MainWindow::loadJsonData);
                           //mainLayout->addWidget(jsonWidget);


/**
                          const char* fromQstr = country.toUtf8().constData();
                          QLabel *label = new QLabel();
                          label->setText(now["wind_speed"].toString());
                          label->show();
**/
                        qDebug() << "last update:" << last_update << "country:" << country;
                        qDebug() << "id:" << id << "name:" << name;
                        qDebug() << "timezones:" << timezone << "timezone_offset:" << timezone_offset;
                        qDebug() << "clouds:" << clouds << "code:" << code;
                        qDebug() << "dew_point:" << dew_point << "feels_like:" << feels_like;


                    }
                }

    } else {
        qDebug() << "Error:" << reply->errorString();
    }
  //  reply->deleteLater(); // 不再需要时删除reply对象
}


}
void MainWindow::onButtonClicked() {
    //Set_sql();
    //QLabel *label = new QLabel(this);
    //LocationInfo local[0];
    //label->setText(QString(LocationInfo->country));
    qDebug() << "Button was clicked!";
}


void MainWindow::updateTimeDisplay() {
    timeLabel->setText(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"));
}

MainWindow::~MainWindow()
{
    
    delete ui;
}

